<template>
  <div class="recommendation-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>智能推荐系统</h2>
        <p>基于机器学习算法的个性化推荐，提升用户体验和转化率</p>
      </div>
      <div class="header-actions">
        <el-button :icon="Refresh" @click="() => refreshData(true)">刷新数据</el-button>
        <el-button type="primary" :icon="MagicStick" @click="runRecommendation" :loading="recommending">
          执行推荐
        </el-button>
        <el-button :icon="Download" @click="exportResults">导出结果</el-button>
      </div>
    </div>

    <!-- 推荐概览统计 - 横向卡片布局 -->
    <div class="overview-section">
      <div class="overview-cards">
        <div class="overview-card primary">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="card-info">
              <h3>{{ overviewData.totalRecommendations.toLocaleString() }}</h3>
              <p>总推荐数</p>
              <span class="trend-up">+{{ overviewData.recommendationChange }}%</span>
            </div>
          </div>
        </div>

        <div class="overview-card success">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Mouse /></el-icon>
            </div>
            <div class="card-info">
              <h3>{{ overviewData.clickRate }}%</h3>
              <p>点击率</p>
              <span class="trend-up">+{{ overviewData.clickRateChange }}%</span>
            </div>
          </div>
        </div>

        <div class="overview-card warning">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="card-info">
              <h3>{{ overviewData.conversionRate }}%</h3>
              <p>转化率</p>
              <span class="trend-up">+{{ overviewData.conversionChange }}%</span>
            </div>
          </div>
        </div>

        <div class="overview-card danger">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="card-info">
              <h3>¥{{ overviewData.revenueImpact.toLocaleString() }}</h3>
              <p>收入贡献</p>
              <span class="trend-up">+{{ overviewData.revenueChange }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 - 三列布局 -->
    <div class="main-content">
      <!-- 左侧：算法选择和配置 -->
      <div class="left-panel">
        <div class="algorithm-selection-panel">
          <h3>推荐算法</h3>
          <div class="algorithm-tabs">
            <div
              v-for="algorithm in availableAlgorithms"
              :key="algorithm.name"
              class="algorithm-tab"
              :class="{ active: algorithm.name === selectedAlgorithm }"
              @click="selectedAlgorithm = algorithm.name"
            >
              <div class="tab-header">
                <h4>{{ algorithm.displayName }}</h4>
                <div class="tab-status">{{ algorithm.status }}</div>
              </div>
              <div class="tab-description">
                <span>{{ algorithm.description }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="quick-config-panel">
          <h3>快速配置</h3>
          <div class="config-form">
            <div class="config-item">
              <label>推荐数量</label>
              <el-input-number
                v-model="algorithmConfig.recommendCount"
                :min="1"
                :max="50"
                size="small"
              />
            </div>
            <div class="config-item">
              <label>相似度阈值</label>
              <el-slider
                v-model="algorithmConfig.similarityThreshold"
                :min="0"
                :max="1"
                :step="0.1"
                :format-tooltip="formatSimilarityTooltip"
              />
            </div>
            <div class="config-item">
              <label>多样性权重</label>
              <el-slider
                v-model="algorithmConfig.diversityWeight"
                :min="0"
                :max="1"
                :step="0.1"
                :format-tooltip="formatDiversityTooltip"
              />
            </div>
            <div class="config-item">
              <label>时间衰减</label>
              <el-switch v-model="algorithmConfig.timeDecay" />
            </div>
          </div>
        </div>
      </div>

      <!-- 中间：推荐效果趋势 -->
      <div class="center-panel">
        <div class="trend-chart-panel">
          <div class="panel-header">
            <h3>推荐效果趋势</h3>
            <el-radio-group v-model="trendTimeRange" size="small">
              <el-radio-button label="7d">7天</el-radio-button>
              <el-radio-button label="30d">30天</el-radio-button>
              <el-radio-button label="90d">90天</el-radio-button>
            </el-radio-group>
          </div>
          <div class="chart-wrapper">
            <LineChart
              :data="trendChartData"
              :x-axis-data="trendLabels"
              height="320px"
            />
          </div>
        </div>


      </div>

      <!-- 右侧：热门推荐和实时数据 -->
      <div class="right-panel">
        <div class="hot-products-panel">
          <div class="panel-header">
            <h3>热门推荐</h3>
            <el-select v-model="hotProductsCategory" size="small">
              <el-option label="全部" value="all" />
              <el-option label="电子产品" value="electronics" />
              <el-option label="服装" value="clothing" />
              <el-option label="家居" value="home" />
              <el-option label="美妆" value="beauty" />
            </el-select>
          </div>
          <div class="products-grid" v-if="filteredHotProducts.length > 0">
            <div
              v-for="product in filteredHotProducts.slice(0, 6)"
              :key="product.id"
              class="product-card"
            >
              <img :src="product.image" :alt="product.name" class="product-img" />
              <div class="product-details">
                <h4>{{ product.name }}</h4>
                <p class="category">{{ product.category }}</p>
                <div class="product-stats">
                  <span class="price">¥{{ product.price.toLocaleString() }}</span>
                  <span class="click-rate">{{ product.clickRate }}%</span>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="empty-state">
            <el-icon class="empty-icon"><Box /></el-icon>
            <p>暂无热门产品数据</p>
            <p class="empty-tip">请先执行推荐生成产品数据</p>
          </div>
        </div>


      </div>
    </div>

    <!-- 用户推荐列表 -->
    <el-card class="recommendation-list-card">
      <template #header>
        <div class="card-header">
          <h3>用户推荐列表</h3>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户ID或姓名"
              :prefix-icon="Search"
              style="width: 200px; margin-right: 12px;"
              clearable
            />
            <el-select v-model="algorithmFilter" placeholder="推荐算法" style="width: 150px; margin-right: 12px;">
              <el-option label="全部" value="" />
              <el-option label="协同过滤" value="collaborative" />
              <el-option label="内容推荐" value="content" />
              <el-option label="混合推荐" value="hybrid" />
            </el-select>
            <el-select v-model="statusFilter" placeholder="推荐状态" style="width: 120px;">
              <el-option label="全部" value="" />
              <el-option label="已推荐" value="recommended" />
              <el-option label="已点击" value="clicked" />
              <el-option label="已购买" value="purchased" />
            </el-select>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="filteredRecommendations" 
        v-loading="loading"
        stripe
        @sort-change="handleSortChange"
      >
        <el-table-column prop="userId" label="用户ID" min-width="100" />
        <el-table-column prop="userName" label="用户姓名" min-width="120" />
        <el-table-column prop="algorithm" label="推荐算法" min-width="120">
          <template #default="{ row }">
            <el-tag :type="getAlgorithmTagType(row.algorithm)">
              {{ getAlgorithmDisplayName(row.algorithm) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="recommendedItems" label="推荐产品数" min-width="120" />
        <el-table-column prop="clickRate" label="点击率" min-width="100" sortable>
          <template #default="{ row }">
            {{ row.clickRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="conversionRate" label="转化率" min-width="100" sortable>
          <template #default="{ row }">
            {{ row.conversionRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="revenue" label="产生收入" min-width="120" sortable>
          <template #default="{ row }">
            ¥{{ row.revenue.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="lastRecommendTime" label="最后推荐时间" min-width="140" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewRecommendationDetail(row)">详情</el-button>
            <el-button size="small" type="primary" @click="updateRecommendation(row)">
              更新推荐
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalRecommendations"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 推荐详情弹窗 -->
    <el-dialog
      v-model="recommendationDetailVisible"
      title="推荐详情"
      width="80%"
      :before-close="handleCloseRecommendationDetail"
    >
      <div v-if="selectedRecommendation" class="recommendation-detail-content">
        <h3>推荐详情</h3>
        <p>用户ID: {{ selectedRecommendation.userId }}</p>
        <p>用户姓名: {{ selectedRecommendation.userName }}</p>
        <p>推荐算法: {{ getAlgorithmDisplayName(selectedRecommendation.algorithm) }}</p>
        <p>点击率: {{ selectedRecommendation.clickRate }}%</p>
        <p>转化率: {{ selectedRecommendation.conversionRate }}%</p>
        <p>产生收入: ¥{{ selectedRecommendation.revenue.toLocaleString() }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh, MagicStick, Download, Star, Mouse, ShoppingCart, Money, Search, Box
} from '@element-plus/icons-vue'
import { LineChart } from '@/components/charts'

// 导入API
import {
  getRecommendationOverview,
  getTrendData,
  getHotProducts,
  getUserRecommendations,
  runRecommendation as executeRecommendation
} from '@/api/recommendation'

// 导入子组件（暂时注释掉避免异步加载问题）
// import RecommendationDetailPanel from '@/components/recommendation/RecommendationDetailPanel.vue'

// 响应式数据
const loading = ref(false)
const recommending = ref(false)
const recommendationDetailVisible = ref(false)
const selectedRecommendation = ref(null)

// 筛选和搜索
const searchKeyword = ref('')
const algorithmFilter = ref('')
const statusFilter = ref('')
const trendTimeRange = ref('30d')
const selectedAlgorithm = ref('collaborative')
const hotProductsCategory = ref('all')

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalRecommendations = ref(0)

// 概览数据
const overviewData = reactive({
  totalRecommendations: 125680,
  recommendationChange: 18.5,
  clickRate: 12.8,
  clickRateChange: 5.2,
  conversionRate: 3.6,
  conversionChange: 8.9,
  revenueImpact: 2850000,
  revenueChange: 25.3
})

// 算法配置
const algorithmConfig = reactive({
  recommendCount: 10,
  similarityThreshold: 0.7,
  timeDecay: true,
  diversityWeight: 0.3
})

// 可用算法列表
const availableAlgorithms = ref([
  {
    name: 'collaborative',
    displayName: '协同过滤',
    description: '基于用户行为相似性推荐',
    status: '已启用'
  },
  {
    name: 'content_based',
    displayName: '内容推荐',
    description: '基于商品特征相似性推荐',
    status: '已启用'
  },
  {
    name: 'hybrid',
    displayName: '混合推荐',
    description: '结合多种算法的混合推荐',
    status: '已启用'
  }
])

// 趋势数据
const trendLabels = ref(['1月1日', '1月2日', '1月3日', '1月4日', '1月5日', '1月6日', '1月7日'])

const trendChartData = ref([
  {
    name: '点击率',
    data: [12.5, 13.2, 12.8, 14.1, 13.9, 14.5, 15.2]
  },
  {
    name: '转化率',
    data: [3.2, 3.5, 3.1, 3.8, 3.6, 4.1, 4.3]
  },
  {
    name: '收入贡献',
    data: [85, 92, 88, 96, 94, 102, 108]
  }
])

// 热门推荐产品
const hotProducts = ref([
  {
    id: 'P001',
    name: 'iPhone 15 Pro',
    category: '电子产品',
    price: 7999,
    image: '/api/placeholder/60/60',
    recommendCount: 1250,
    clickRate: 18.5
  },
  {
    id: 'P002',
    name: '羽绒服外套',
    category: '服装',
    price: 599,
    image: '/api/placeholder/60/60',
    recommendCount: 890,
    clickRate: 15.2
  },
  {
    id: 'P003',
    name: '智能手表',
    category: '电子产品',
    price: 2299,
    image: '/api/placeholder/60/60',
    recommendCount: 650,
    clickRate: 22.1
  },
  {
    id: 'P004',
    name: '护肤套装',
    category: '美妆',
    price: 299,
    image: '/api/placeholder/60/60',
    recommendCount: 1100,
    clickRate: 12.8
  },
  {
    id: 'P005',
    name: '咖啡机',
    category: '家居',
    price: 1299,
    image: '/api/placeholder/60/60',
    recommendCount: 420,
    clickRate: 16.7
  }
])

// 用户推荐列表数据
const userRecommendations = ref([
  {
    userId: 'U001234',
    userName: '张三',
    algorithm: 'collaborative',
    recommendedItems: 8,
    clickRate: 15.5,
    conversionRate: 4.2,
    revenue: 1299,
    lastRecommendTime: '2024-01-15 14:30'
  },
  {
    userId: 'U001235',
    userName: '李四',
    algorithm: 'content',
    recommendedItems: 10,
    clickRate: 18.2,
    conversionRate: 5.8,
    revenue: 2599,
    lastRecommendTime: '2024-01-15 13:45'
  },
  {
    userId: 'U001236',
    userName: '王五',
    algorithm: 'hybrid',
    recommendedItems: 12,
    clickRate: 22.1,
    conversionRate: 6.5,
    revenue: 3299,
    lastRecommendTime: '2024-01-15 12:20'
  },
  {
    userId: 'U001237',
    userName: '赵六',
    algorithm: 'deep_learning',
    recommendedItems: 9,
    clickRate: 25.8,
    conversionRate: 8.2,
    revenue: 4599,
    lastRecommendTime: '2024-01-15 11:15'
  },
  {
    userId: 'U001238',
    userName: '钱七',
    algorithm: 'collaborative',
    recommendedItems: 7,
    clickRate: 12.3,
    conversionRate: 2.8,
    revenue: 899,
    lastRecommendTime: '2024-01-15 10:30'
  }
])

// 计算属性
const filteredHotProducts = computed(() => {
  if (hotProductsCategory.value === 'all') {
    return hotProducts.value
  }

  const categoryMap = {
    'electronics': '电子产品',
    'clothing': '服装',
    'home': '家居',
    'beauty': '美妆'
  }

  return hotProducts.value.filter(product =>
    product.category === categoryMap[hotProductsCategory.value]
  )
})



const filteredRecommendations = computed(() => {
  let filtered = userRecommendations.value

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(rec =>
      rec.userId.toLowerCase().includes(keyword) ||
      rec.userName.toLowerCase().includes(keyword)
    )
  }

  // 算法过滤
  if (algorithmFilter.value) {
    filtered = filtered.filter(rec => rec.algorithm === algorithmFilter.value)
  }

  // 状态过滤（这里简化处理，实际应该根据具体状态字段过滤）
  if (statusFilter.value) {
    // 根据不同状态进行过滤逻辑
  }

  return filtered
})

// 方法
const refreshData = async (showMessage = false) => {
  loading.value = true
  try {
    // 并行加载所有数据
    await Promise.all([
      loadOverviewData(),
      loadTrendData(),
      loadHotProducts(),
      loadUserRecommendations()
    ])

    if (showMessage) {
      ElMessage.success('数据刷新成功')
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

// 加载概览数据
const loadOverviewData = async () => {
  try {
    const response = await getRecommendationOverview()
    if (response.success && response.data) {
      Object.assign(overviewData, response.data)
    }
  } catch (error) {
    console.error('加载概览数据失败:', error)
  }
}



// 加载趋势数据
const loadTrendData = async () => {
  try {
    const response = await getTrendData({ timeRange: trendTimeRange.value })
    if (response.success && response.data && Array.isArray(response.data)) {
      // 更新趋势图表数据
      trendLabels.value = response.data.map(item => item.date)
      trendChartData.value = [
        {
          name: '推荐数',
          data: response.data.map(item => item.recommendations),
          color: '#5470c6'
        },
        {
          name: '点击数',
          data: response.data.map(item => item.clicks),
          color: '#91cc75'
        },
        {
          name: '转化数',
          data: response.data.map(item => item.conversions),
          color: '#fac858'
        }
      ]
    }
  } catch (error) {
    console.error('加载趋势数据失败:', error)
  }
}

// 加载热门产品数据
const loadHotProducts = async () => {
  try {
    const response = await getHotProducts({ category: hotProductsCategory.value })
    if (response.success && response.data && Array.isArray(response.data)) {
      hotProducts.value = response.data
    }
  } catch (error) {
    console.error('加载热门产品数据失败:', error)
  }
}

// 加载用户推荐列表
const loadUserRecommendations = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      searchKeyword: searchKeyword.value,
      algorithmFilter: algorithmFilter.value,
      statusFilter: statusFilter.value
    }

    const response = await getUserRecommendations(params)
    if (response.success && response.data) {
      userRecommendations.value = response.data.recommendations || []
      const pagination = response.data.pagination || {}
      totalRecommendations.value = pagination.total_count || 0
    } else {
      userRecommendations.value = []
      totalRecommendations.value = 0
    }
  } catch (error) {
    console.error('加载用户推荐列表失败:', error)
    userRecommendations.value = []
    totalRecommendations.value = 0
  }
}

const runRecommendation = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要执行推荐吗？这将为所有用户生成个性化推荐结果。',
      '确认执行推荐',
      { type: 'warning' }
    )

    recommending.value = true

    const response = await executeRecommendation()
    if (response.success) {
      ElMessage.success(response.message)
      // 刷新数据
      await refreshData()
    } else {
      ElMessage.error(response.message || '推荐执行失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('执行推荐失败:', error)
      ElMessage.error('推荐执行失败')
    }
  } finally {
    recommending.value = false
  }
}

const exportResults = () => {
  // 导出推荐结果
  const data = filteredRecommendations.value
  const csvContent = [
    ['用户ID', '用户姓名', '推荐算法', '推荐产品数', '点击率', '转化率', '产生收入', '最后推荐时间'],
    ...data.map(rec => [
      rec.userId,
      rec.userName,
      rec.algorithm,
      rec.recommendedItems,
      rec.clickRate,
      rec.conversionRate,
      rec.revenue,
      rec.lastRecommendTime
    ])
  ].map(row => row.join(',')).join('\n')

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `recommendation_results_${new Date().toISOString().split('T')[0]}.csv`
  link.click()

  ElMessage.success('推荐结果已导出')
}

const getAlgorithmDisplayName = (algorithm) => {
  const nameMap = {
    'collaborative': '协同过滤',
    'content': '内容推荐',
    'hybrid': '混合推荐',
    'deep_learning': '深度学习'
  }
  return nameMap[algorithm] || algorithm
}

const getAlgorithmTagType = (algorithm) => {
  const typeMap = {
    'collaborative': 'primary',
    'content': 'success',
    'hybrid': 'warning',
    'deep_learning': 'danger'
  }
  return typeMap[algorithm] || 'info'
}

const formatSimilarityTooltip = (value) => {
  return `${value} 相似度`
}

const formatDiversityTooltip = (value) => {
  return `${value} 多样性`
}



const viewRecommendationDetail = (recommendation) => {
  selectedRecommendation.value = {
    ...recommendation,
    // 添加详细推荐数据
    recommendedProducts: [
      { id: 'P001', name: 'iPhone 15 Pro', score: 0.95, clicked: true, purchased: false },
      { id: 'P002', name: '无线耳机', score: 0.88, clicked: true, purchased: true },
      { id: 'P003', name: '智能手表', score: 0.82, clicked: false, purchased: false }
    ],
    userProfile: {
      age: 28,
      gender: '男',
      location: '北京',
      preferences: ['电子产品', '数码配件']
    }
  }
  recommendationDetailVisible.value = true
}

const updateRecommendation = async (recommendation) => {
  try {
    await ElMessageBox.confirm(
      `确定要为用户 ${recommendation.userName} 更新推荐吗？`,
      '确认更新',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 模拟更新推荐
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('推荐更新成功')

    // 刷新数据
    await refreshData(false)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('推荐更新失败')
    }
  }
}

const handleCloseRecommendationDetail = () => {
  recommendationDetailVisible.value = false
  selectedRecommendation.value = null
}

const handleUpdateRecommendation = (recommendation) => {
  ElMessage.success('推荐已更新')
  recommendationDetailVisible.value = false
}

const handleExportRecommendationData = (recommendation) => {
  // 导出单个用户的推荐数据
  const data = JSON.stringify(recommendation, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)

  const link = document.createElement('a')
  link.href = url
  link.download = `recommendation_${recommendation.userId}_detail.json`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)

  ElMessage.success('推荐数据已导出')
}

const handleSortChange = ({ column, prop, order }) => {
  // 实现排序逻辑
  console.log('排序变化:', { column, prop, order })
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 监听器
watch([trendTimeRange, selectedAlgorithm], () => {
  // 根据时间范围和算法更新数据
  refreshData()
})

// 监听器
watch([trendTimeRange], () => {
  // 时间范围变化时重新加载趋势数据
  loadTrendData()
})

watch([hotProductsCategory], () => {
  // 产品类别变化时重新加载热门产品
  loadHotProducts()
})

watch([searchKeyword, algorithmFilter, statusFilter, currentPage, pageSize], () => {
  // 搜索和筛选条件变化时重新加载用户推荐列表
  loadUserRecommendations()
})

// 生命周期
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.recommendation-page {
  padding: 0;
  background-color: transparent;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 概览统计 - 新的横向卡片布局 */
.overview-section {
  margin-bottom: 32px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.overview-card {
  background: white;
  border-radius: 20px;
  padding: 0;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
  position: relative;
}

.overview-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.overview-card.primary {
  background: #667eea !important;
}

.overview-card.success {
  background: #f5576c !important;
}

.overview-card.warning {
  background: #4facfe !important;
}

.overview-card.danger {
  background: #43e97b !important;
}

.card-content {
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  color: white !important;
}

.card-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  backdrop-filter: blur(10px);
}

.card-info h3 {
  margin: 0 0 4px 0;
  font-size: 28px;
  font-weight: 700;
  color: white !important;
}

.card-info p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9) !important;
}

.trend-up {
  font-size: 12px;
  font-weight: 600;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.3) !important;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  color: white !important;
}

/* 三列布局 */
.main-content {
  display: grid;
  grid-template-columns: 300px 1fr 320px;
  gap: 20px;
  margin-bottom: 32px; /* 适中的底部边距 */
  align-items: stretch; /* 让所有列高度一致 */
  height: 600px; /* 固定高度确保底部对齐 */
  position: relative;
}

/* 左侧面板 */
.left-panel {
  display: flex;
  flex-direction: column;
  gap: 16px; /* 减少间距 */
  height: 100%; /* 填满容器高度 */
  max-height: 600px; /* 严格限制最大高度 */
  overflow: hidden; /* 防止内容溢出 */
}

.algorithm-selection-panel,
.quick-config-panel {
  background: white;
  border-radius: 16px;
  padding: 16px; /* 减少内边距 */
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
}

.algorithm-selection-panel {
  flex: 0 0 350px; /* 增加到350px */
  overflow-y: auto;
}

.quick-config-panel {
  flex: 0 0 234px; /* 调整到234px，总计350+234+16=600px */
  overflow-y: auto;
}

.algorithm-selection-panel h3,
.quick-config-panel h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.algorithm-tabs {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.algorithm-tab {
  padding: 12px;
  border: 2px solid #f0f0f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.algorithm-tab:hover {
  border-color: #409EFF;
  background: #f0f9ff;
}

.algorithm-tab.active {
  border-color: #409EFF;
  background: linear-gradient(135deg, #f0f9ff, #e6f4ff);
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.tab-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}



.tab-description {
  margin-top: 4px;
}

.tab-description span {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.tab-status {
  font-size: 11px;
  color: #67C23A;
  background: rgba(103, 194, 58, 0.1);
  padding: 2px 8px;
  border-radius: 8px;
}

/* 配置表单 */
.config-form {
  display: flex;
  flex-direction: column;
  gap: 12px; /* 减少间距 */
  flex: 1;
  overflow-y: auto;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 6px; /* 减少间距 */
}

.config-item label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

/* 中间面板 */
.center-panel {
  display: flex;
  flex-direction: column;
  height: 100%; /* 填满容器高度，与左右面板对齐 */
}

.trend-chart-panel {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  height: 100%; /* 填满容器高度 */
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.panel-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.chart-wrapper {
  flex: 1; /* 填充剩余空间 */
  min-height: 300px;
}



/* 右侧面板 */
.right-panel {
  display: flex;
  flex-direction: column;
  height: 100%; /* 填满容器高度 */
}

.hot-products-panel {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  height: 100%; /* 占据整个右侧面板高度 */
  overflow: hidden;
  display: flex;
  flex-direction: column;
}



.hot-products-panel .panel-header h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

/* 产品网格 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  flex: 1;
  overflow-y: auto;
  padding-right: 4px;
}

.product-card {
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  background: white;
  height: fit-content;
}

.product-card:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
  transform: translateY(-2px);
}

.product-img {
  width: 100%;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 8px;
  background: #f5f5f5;
}

.product-details h4 {
  margin: 0 0 4px 0;
  font-size: 12px;
  font-weight: 600;
  color: #333;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-details .category {
  margin: 0 0 8px 0;
  font-size: 10px;
  color: #666;
}

.product-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-stats .price {
  font-size: 12px;
  font-weight: 600;
  color: #f56c6c;
}

.product-stats .click-rate {
  font-size: 10px;
  color: #67C23A;
  background: rgba(103, 194, 58, 0.1);
  padding: 2px 6px;
  border-radius: 8px;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  color: #999;
  flex: 1;
}

/* 推荐列表卡片 */
.recommendation-list-card {
  margin-top: 0; /* 移除额外的顶部边距 */
  clear: both; /* 确保不与浮动元素重叠 */
  position: relative;
  z-index: 1; /* 确保在最上层 */
}

.empty-icon {
  font-size: 48px;
  color: #ddd;
  margin-bottom: 16px;
}

.empty-state p {
  margin: 4px 0;
  font-size: 14px;
}

.empty-tip {
  font-size: 12px !important;
  color: #bbb !important;
}



/* 算法配置 */
.algorithm-config {
  padding: 20px 0;
}

.algorithm-config .el-form-item {
  margin-bottom: 20px;
}

.algorithm-config .el-slider {
  margin-right: 20px;
}

/* 图表容器 */
.chart-container {
  padding: 20px;
  height: 400px;
}

/* 推荐效果趋势卡片特殊样式 */
.chart-card {
  min-height: 500px;
  margin-bottom: 24px;
}

/* 算法配置卡片 */
.algorithm-config-card {
  min-height: 280px;
}

/* 右侧卡片高度调整 */
.performance-card {
  min-height: 400px;
  margin-bottom: 24px;
}

.hot-recommendations-card {
  min-height: 400px;
}

/* 算法性能对比 */
.performance-metrics {
  padding: 20px 0;
}

.performance-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 12px;
  border-radius: 8px;
  border: 2px solid #f0f0f0;
  transition: all 0.3s ease;
  cursor: pointer;
}

.performance-item:last-child {
  margin-bottom: 0;
}

.performance-item:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.performance-item.active {
  border-color: #409EFF;
  background: #f0f9ff;
}

.algorithm-info {
  flex: 1;
}

.algorithm-info h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.metric {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric-label {
  font-size: 12px;
  color: #666;
}

.metric-value {
  font-size: 12px;
  font-weight: 600;
  color: #333;
}

.performance-score {
  margin-left: 20px;
}

/* 热门推荐产品 */
.hot-products-list {
  padding: 20px 0;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.product-item:last-child {
  border-bottom: none;
}

.product-item:hover {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  margin: 0 -12px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.product-image {
  width: 45px;
  height: 45px;
  border-radius: 8px;
  object-fit: cover;
}

.product-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.product-category {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #666;
}

.product-price {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #f56c6c;
}

.product-metrics {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 100px;
  text-align: right;
}

.product-metrics .metric {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.product-metrics .label {
  font-size: 11px;
  color: #666;
  white-space: nowrap;
}

.product-metrics .value {
  font-size: 12px;
  font-weight: 600;
  color: #333;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 280px 1fr 260px;
    gap: 20px;
  }

  .products-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 992px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .left-panel,
  .right-panel {
    order: 2;
  }

  .center-panel {
    order: 1;
  }

  .overview-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }

  .overview-cards {
    grid-template-columns: 1fr;
  }

  .main-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .products-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .algorithm-tabs {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .radar-metrics {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .radar-item {
    padding: 12px;
  }
}

@media (max-width: 480px) {
  .overview-cards {
    gap: 16px;
  }

  .card-content {
    padding: 20px;
  }

  .card-info h3 {
    font-size: 24px;
  }

  .products-grid {
    grid-template-columns: 1fr;
  }

  .algorithm-tabs {
    grid-template-columns: 1fr;
  }

  .config-form {
    gap: 12px;
  }
}
</style>
